package com.yht.redbook.data.align.consumer;

import com.yht.framework.common.utils.JsonUtils;
import com.yht.redbook.data.align.constant.MQConstants;
import com.yht.redbook.data.align.constant.RedisKeyConstants;
import com.yht.redbook.data.align.constant.TableConstants;
import com.yht.redbook.data.align.domain.mapper.InsertRecordMapper;
import com.yht.redbook.data.align.model.dto.FollowUnfollowMqDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Objects;

@RocketMQMessageListener(consumerGroup = "redbook_group_data_align_" + MQConstants.TOPIC_COUNT_FOLLOWING,
        topic = MQConstants.TOPIC_COUNT_FOLLOWING)
@Slf4j
@Component
public class TodayNoteFollowingIncrementData2DBConsumer implements RocketMQListener<String> {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private InsertRecordMapper insertRecordMapper;

    @Value("${table.shards}")
    private int tableShards;

    @Override
    public void onMessage(String body) {
        log.info("## TodayNoteFollowingIncrementData2DBConsumer 消费到了 MQ: {}", body);

        // --------------- 源用户的关注数变更记录 -----------------------
        // 1.布隆过滤器判断该日增量数据是否已经记录，若无才会落库，减轻数据库压力
        FollowUnfollowMqDTO followUnfollowMqDTO = JsonUtils.parseObject(body, FollowUnfollowMqDTO.class);
        if (Objects.isNull(followUnfollowMqDTO)) return;

        Long userId = followUnfollowMqDTO.getUserId();
        Long targetUserId = followUnfollowMqDTO.getTargetUserId();

        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String bloomUserFollowListKey = RedisKeyConstants.buildBloomUserFollowListKey(date);
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setResultType(Long.class);
        script.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/bloom_today_user_follow_check.lua")));

        Long result = redisTemplate.execute(script, Collections.singletonList(bloomUserFollowListKey), userId);

        RedisScript<Long> bloomAddScript = RedisScript.of("return redis.call('BF.ADD'), KEYS[1], ARGV[1]", Long.class);

        if (Objects.equals(result, 0L)) {
            // 若布隆过滤器判断不存在，才会落库，减轻数据库压力
            // 将日增量变更数据，写入表 t_data_align_following_count_temp_日期_分片序号
            // 数据库写入成功后，再添加到布隆过滤器中
            long userIdHashKey = userId % tableShards;

            try {
                // 将日增量变更数据，写入 t_data_align_following_count_temp 表中
                insertRecordMapper.insert2DataAlignUserFollowingCountTemplate(TableConstants.buildTableNameSuffix(date, userIdHashKey), userId);
            } catch (Exception e) {
                log.error("", e);
            }
        }

        // 3.数据库写入成功后，再添加至布隆过滤器中
        redisTemplate.execute(bloomAddScript, Collections.singletonList(bloomUserFollowListKey), userId);

        // --------------- 源用户的粉丝数变更记录 -----------------------
        // 1.布隆过滤器判断该日增量数据是否已经记录，若无才会落库，减轻数据库压力
        String bloomUserFansListKey = RedisKeyConstants.buildBloomUserNoteFansListKey(date);
        DefaultRedisScript<Long> script1 = new DefaultRedisScript<>();
        Long result1 = redisTemplate.execute(script1, Collections.singletonList(bloomUserFansListKey), targetUserId);

        if (Objects.equals(result1, 0L)) {
            // 若布隆过滤器判断不存在，才会落库，减轻数据库压力
            // 将日增量变更数据，写入表 t_data_align_fans_count_temp_日期_分片序号
            // 数据库写入成功后，再添加到布隆过滤器中
            long targetUserIdHashKey = targetUserId % tableShards;
            try {
                insertRecordMapper.insert2DataAlignUserFansCountTemplate(TableConstants.buildTableNameSuffix(date, targetUserIdHashKey), targetUserId);
            } catch (Exception e) {
                log.error("", e);
            }
        }

        // 3.数据库写入成功后，再添加至布隆过滤器中
        redisTemplate.execute(bloomAddScript, Collections.singletonList(bloomUserFansListKey), targetUserId);
    }
}
